from .const import ER

'''
TODO 看是否要统一定义错误，待定
'''

class Warning(Warning):
    """Exception raised for important warnings like data truncations
    while inserting, etc."""

class Error(Exception):
    """Exception that is the base class of all other error exceptions
    (not Warning)."""

class InternalError(Error):
    """Exception raised when the backend server encounters an internal
    error, e.g. segment overflow, any other operation that cannot be 
    defined etc."""

class UnknownError(Error):
    """Exception raised when the backend server encounters an undefines
    error"""

class DatabaseError(Error):
    """Exception raised for errors that are related to the
    database. """

class DuplicateError(Error):
    """Exception raised for errors that sql database encounters
    (1062, duplicate xxx) error"""

class HttpError(Error):
    """Exception raised for errors that are related to the
    http/https api access error, like cannot access, etc. """

class ValueMissError(Error):
    """Exception raised for important value miss error...."""

class JobError(Error):
    """Exception raised for job running related error...."""


error_map = {}

def _map_error(exc, *errors):
    for error in errors:
        error_map[error] = exc
        
_map_error(
    UnknownError,
    ER.ERROR_UNKNOWN,
)
# DB 类错误
_map_error(
    DatabaseError,
    ER.DB_ERROR,
)
_map_error(
    DuplicateError,
    ER.DB_DUPLICATED,
)
# HTTP类错误
_map_error(
    HttpError,
    ER.HTTP_ERROR,
)
# 值相关错误, 这种错误尽量返回BadRequestResponse
_map_error(
    ValueMissError,
    ER.VALUE_ERROR,
    ER.VALUE_MISS_DOMAIN_VALUE,
    ER.VALUE_ANALYSIS_TOKEN_INVALID,
    ER.VALUE_ANALYSIS_ACTION_NOT_EXIST,
    ER.VALUE_ANALYSIS_JOB_ID_NOT_EXIST,
)
# job任务工作相关的错误
_map_error(
    JobError,
    ER.JOB_ERROR,
    ER.JOB_NOT_START,
    ER.JOB_SSH_EXECUTE_ERROR,
)



# 暂定data=tuple(errno, errval)
def raise_exception(data):
    errno = data[0]
    errval = data[1]
    errorclass = error_map.get(errno)
    if errorclass is None:
        errorclass = InternalError if errno < ER.ERROR_FIRST else UnknownError
    raise errorclass(errno, errval)